import COS from 'cos-js-sdk-v5'
import { publishApi } from '@/api/api'
import { getUuid } from '@/utils'
import request from '@/utils/request'
let cacheList = []
let status = false
// 防止重复请求获取临时秘钥的接口
async function getAuthorization() {
  if (status) {
    return new Promise((resolve) => {
      cacheList.push((data) => {
        resolve(data)
      })
    })
  } else {
    status = true
    const { data } = await request(publishApi.getTempCredential, {}, { unCheckCode: true })
    cacheList.forEach((item) => {
      item(data)
    })
    cacheList = []
    status = false
    return data
  }
}

const cos = new COS({
  getAuthorization: async (options, callback) => {
    const data = await getAuthorization()
    callback({
      TmpSecretId: data.tmpSecretId,
      TmpSecretKey: data.tmpSecretKey,
      XCosSecurityToken: data.sessionToken,
      StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
      ExpiredTime: data.expiredTime // 时间戳，单位秒，如：1580000900
    })
  }
})

const defaultBucket = 'it-platform-1300554927' //默认存储桶
const defaultRegion = 'ap-chengdu' //默认桶所在区域
// 获取文件名后缀
function getExt(fileName) {
  const arr = fileName.split('.')
  return arr[arr.length - 1]
}
// 与el-upload配合使用的上传方法
export function upload(option) {
  const now = new Date()
  // const date = '/' + now.getFullYear() + '-' + (now.getMonth() + 1)
  const date = now.getFullYear() + '-' + (now.getMonth() + 1)
  const key = option.action + date + '/' + getUuid() + '.' + getExt(option.file.name)
  const { data } = option.data
  const Bucket = data ? option.data.Bucket || defaultBucket : defaultBucket
  const Region = data ? option.data.Region || defaultRegion : defaultRegion
  cos.putObject(
    {
      Bucket: Bucket,
      Region: Region,
      Key: key,
      Body: option.file,
      onProgress: (e) => {
        if (e.total > 0) {
          e.percent = (e.loaded / e.total) * 100
        }
        option.onProgress(e)
      }
    },
    (err, data) => {
      if (err) {
        option.onError(err)
      } else {
        data.key = key
        option.onSuccess(data)
      }
    }
  )
}
// 获取文件链接
export async function getObjectUrl(data, keyList, sign = true) {
  const res = await Promise.all(
    keyList.map((key) => {
      return new Promise((resolve) => {
        cos.getObjectUrl(
          {
            Bucket: data.Bucket || defaultBucket,
            Region: data.Region || defaultRegion,
            Key: key,
            Sign: sign
            // Expires: 3600 // 单位秒
          },
          function (err, data) {
            if (err) {
              resolve(data)
            } else {
              resolve(data.Url)
            }
          }
        )
      })
    })
  )
  return res
}
// 下载文件
export async function getObject(data, keyList) {
  const res = await Promise.all(
    keyList.map((key) => {
      return new Promise((resolve) => {
        cos.getObject(
          {
            Bucket: data.Bucket || defaultBucket,
            Region: data.Region || defaultRegion,
            Key: key
          },
          function (err, data) {
            if (err) {
              resolve(data)
            } else {
              resolve(data)
            }
          }
        )
      })
    })
  )
  return res
}

// 将临时文件移动到项目文件夹
export function putObjectCopy(data, locations) {
  return Promise.all(
    locations.map((CopySource) => {
      const env = {
        development: 'Dev',
        production: 'Pro',
        test: 'Test'
      }[process.env.NODE_ENV]
      const newkey = CopySource.replace(/^([^/]*)\//, '').replace(/\/Temp\//, `/${env}/`)
      return new Promise((resolve, reject) => {
        cos.putObjectCopy(
          {
            Bucket: data.Bucket || defaultBucket,
            Region: data.Region || defaultRegion,
            Key: newkey,
            CopySource: CopySource
          },
          (err, data) => {
            if (err) {
              reject(err)
            } else {
              data.key = newkey
              resolve(data)
            }
          }
        )
      })
    })
  )
}
// 删除多个文件
export function deleteMultipleObject(data, keyList) {
  return new Promise((resolve, reject) => {
    cos.deleteMultipleObject(
      {
        Bucket: data.Bucket || defaultBucket,
        Region: data.Region || defaultRegion,
        Objects: keyList.map((item) => {
          return { Key: item }
        })
      },
      (err, data) => {
        if (err) {
          reject(err)
        } else {
          resolve(data)
        }
      }
    )
  })
}
